package com.vim.modules.web.controller;

import com.vim.common.config.WeixinConstants;
import com.vim.common.msg.EventDispatcher;
import com.vim.common.utils.MessageUtil;
import com.vim.common.msg.MsgDispatcher;
import com.vim.common.utils.SignUtils;
import com.vim.common.utils.WeixinUtils;
import com.vim.modules.web.model.WeixinUser;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 微信服务器
 */
@RestController
@RequestMapping(value = "/weixin")
public class WeixinServerController {

    //验证服务
    @RequestMapping(method = RequestMethod.GET)
    public void get(HttpServletRequest request, HttpServletResponse response){
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        PrintWriter out = null;
        try {
            out = response.getWriter();
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
            if (SignUtils.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    //消息服务
    @RequestMapping(method = RequestMethod.POST)
    public void post(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();

            Map<String, String> map= MessageUtil.parseXml(request);
            if(WeixinConstants.REQ_MESSAGE_TYPE_EVENT.equals(map.get("MsgType"))){
                out.print(EventDispatcher.processEvent(map));
            }else{
                out.print(MsgDispatcher.processMessage(map));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取用户信息
     */
    @RequestMapping(value = "/userinfo")
    public WeixinUser userinfo(){
        return WeixinUtils.userInfo("oXve1w8YZ6C-J1XKzilSyDs9cHhE");
    }

    /**
     * 获取token
     */
    @RequestMapping(value = "/token")
    public String token(){
        return WeixinUtils.getToken();
    }

    /**
     * 获取用户列表
     */
    @RequestMapping(value = "/userlist")
    public Object userlist(){
        return WeixinUtils.userlist("");
    }

}
